<template>
  <el-form :model="form" :rules="rules" ref="form">
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input
        v-model="form.password"
        type="password"
        placeholder="请输入密码"
        show-password
      ></el-input>
    </el-form-item>

    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input
        v-model="form.confirmPassword"
        type="password"
        placeholder="请再次输入密码"
        show-password
      ></el-input>
    </el-form-item>

    <el-form-item label="推荐人(选填)" prop="referrer">
      <el-input v-model="form.referrer" placeholder="请输入推荐人手机号"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">注册</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      form: {
        phone: '',
        password: '',
        confirmPassword: '',
        referrer: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      },
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 提交注册请求
          this.$emit('success')
        }
      })
    }
  }
}
</script>

<style scoped>
.sms-code-container {
  display: flex;
}

.sms-code-container .el-input {
  flex: 1;
  margin-right: 10px;
}
</style>